package com.hitalkie.teacher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hitalkie.teacher.R;
import com.hitalkie.teacher.adapter.LessonRvAdapter;
import com.hitalkie.teacher.app.TalkieApi;
import com.hitalkie.teacher.app.TalkieApplication;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.model.BaseResponse;
import com.hitalkie.teacher.model.Lesson;
import com.hitalkie.teacher.model.User;
import com.hitalkie.teacher.util.OkHttpManager;
import com.hitalkie.teacher.widget.pageview.OnLastItemVisibleListener;
import com.hitalkie.teacher.widget.pageview.PageRecyclerView;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Date 11/11/2016
 *
 * @author charliema
 */
public class LessonListOfUserActivity extends BaseActivity {

    public static final String EXTRA_USER = "com.hitalkie.talkie.extra.USER";

    private User mUser;
    private String mNext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkSignIn();
        initView();
        initData();
        updateData(true);
    }


    private void initData() {
        mUser = (User) getIntent().getSerializableExtra(EXTRA_USER);

    }

    private void checkSignIn() {
        if (!TalkieApplication.isSignIn()) {
            Toast.makeText(getActivity(), "请先注册或登录", Toast.LENGTH_LONG).show();
            startActivity(new Intent(getActivity(), SignUpActivity.class));
            getActivity().finish();
        }
    }

    private void initView() {
        setContentView(R.layout.view_lesson_list_of_user);


        initTitleBar();
        initSrl();
        initRv();

    }

    private void initTitleBar() {
        findViewById(R.id.viewTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    private void initSrl() {
        ((SwipeRefreshLayout) findViewById(R.id.srl)).setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                updateData(true);
            }
        });

    }


    private void initRv() {
        PageRecyclerView rv = (PageRecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        rv.setAdapter(new LessonRvAdapter());
        rv.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                updateData(false);
            }
        });
        ((LessonRvAdapter)rv.getAdapter()).setOnItemClickListener(new LessonRvAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Lesson data) {
                startActivity(new Intent().setClass(getActivity(), LessonDetailActivity.class).putExtra(LessonDetailActivity.EXTRA_LESSON,data));
            }
        });
    }

    private void updateData(final boolean isRefresh) {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");
        ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(true);
        ((PageRecyclerView) findViewById(R.id.rv)).loadingStatus= PageRecyclerView.State.LOADING;

        String url;
        if (isRefresh) {
            url = TalkieApi.getHost() + TalkieApi.PATH_USER + "/" + mUser.id + "/" + "lessons/" + "?shift=history";
        } else {
            url = TalkieApi.getHost() + mNext;
        }
        Request.Builder reqBuilder = new Request.Builder().url(url);
        OkHttpManager.client.newCall(reqBuilder.build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(false);
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        // loading dialog
                        loadingDialogFragment.dismiss();
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "me resp:" + jsonStr);

                        try {
                            final LessonListResp resp = new Gson().fromJson(jsonStr, LessonListResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        if (resp.lessons == null || resp.lessons.size() == 0) {
                                            Toast.makeText(getActivity(), "列表为空", Toast.LENGTH_LONG).show();
                                        } else {
                                            if (isRefresh) {
                                                // 刷新页面
                                                ((LessonRvAdapter) ((RecyclerView) findViewById(R.id.rv)).getAdapter()).setData(resp.lessons);
                                            } else {
                                                // 加载更多
                                                ((LessonRvAdapter) ((RecyclerView) findViewById(R.id.rv)).getAdapter()).addData(resp.lessons);
                                            }
                                            if (TextUtils.isEmpty(resp.next)) {
                                                // 到了最后一页
                                                ((PageRecyclerView) findViewById(R.id.rv)).loadingStatus = PageRecyclerView.State.END;
                                            } else {
                                                ((PageRecyclerView) findViewById(R.id.rv)).loadingStatus = PageRecyclerView.State.IDLE;
                                            }
                                            mNext = resp.next;
                                        }

                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            new Handler(getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), "无法解析返回的数据", Toast.LENGTH_LONG).show();

                                }
                            }); } finally {
                            new Handler(getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                    ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(false);
                                }
                            });
                        }
                    }
                });
    }

    private static class LessonListResp extends BaseResponse {
        List<Lesson> lessons;
        String next;
    }


}
